import requests
import json
import uuid
import re
from typing import Dict, Optional, Union

class DeviceManagerClient:
    def __init__(self, base_url: str = "http://106.54.59.176/"):
        """
        初始化客户端
        :param base_url: API基础地址，默认 http://106.54.59.176
        """
        self.base_url = base_url.rstrip('/')
    
    @staticmethod
    def get_local_mac() -> Optional[str]:
        """
        获取本机MAC地址（适用于Windows/Linux/MacOS）
        :return: MAC地址字符串（格式：00:11:22:33:44:55）或None
        """
        try:
            # 方法1：通过uuid获取（可能返回虚拟网卡地址）
            mac = ':'.join(re.findall('..', '%012x' % uuid.getnode()))
            if mac != '00:00:00:00:00:00':
                return mac.upper()
            
            # 方法2：通过网络接口获取（需要根据系统实现）
            # 这里可以添加更精确的获取逻辑
            return None
        except:
            return None
    
    def check_mac(self, mac_address: Optional[str] = None) -> Dict[str, Union[str, bool]]:
        """
        检查MAC地址授权状态（自动获取本机MAC或使用指定地址）
        :param mac_address: 可选的MAC地址，不传则自动获取本机MAC
        :return: 包含状态信息的字典
        """
        if mac_address is None:
            mac_address = self.get_local_mac()
            if mac_address is None:
                return {
                    'status': 'error',
                    'message': '无法获取本机MAC地址',
                    'success': False
                }
        
        if not self._validate_mac(mac_address):
            return {
                'status': 'error',
                'message': '无效的MAC地址格式',
                'success': False
            }
        
        url = f"{self.base_url}/check_mac"
        params = {'mac': mac_address}
        
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {
                'status': 'error',
                'message': f"请求失败: {str(e)}",
                'success': False
            }
    
    def save_http_result(self, data: Dict) -> Dict[str, Union[str, bool]]:
        """
        保存结果数据
        :param data: 要保存的JSON数据 (字典格式)
        :return: 包含状态信息的字典
        """
        url = f"{self.base_url}/save_result"
        headers = {'Content-Type': 'application/json'}
        
        try:
            response = requests.post(url, json=data, headers=headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {
                'status': 'error',
                'message': f"请求失败: {str(e)}",
                'success': False
            }
    
    @staticmethod
    def _validate_mac(mac: str) -> bool:
        """验证MAC地址格式"""
        return bool(re.match(r"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", mac))
    
    @staticmethod
    def test_connection(base_url: str = "http://106.54.59.176") -> bool:
        """
        测试API连接是否正常
        :param base_url: API基础地址
        :return: 是否连接成功
        """
        try:
            url = f"{base_url.rstrip('/')}/check_mac?mac=00:11:22:33:44:55"
            response = requests.get(url, timeout=3)
            return response.status_code != 500
        except:
            return False


# 使用示例
if __name__ == "__main__":
    # 初始化客户端
    client = DeviceManagerClient()
    
    # 测试连接
    if not DeviceManagerClient.test_connection():
        print("无法连接到API服务，请检查服务是否运行")
        exit(1)
    
    # 获取本机MAC地址
    local_mac = client.get_local_mac()
    print(f"本机MAC地址: {local_mac}")
    
    # 检查MAC地址（自动获取本机MAC）
    print("\n检查本机MAC地址授权状态...")
    try:
        result = client.check_mac()  # 不传参数则自动获取本机MAC
        print("响应结果:", json.dumps(result, indent=2, ensure_ascii=False))
    except:
        print('异常了')
    data = json.dumps(result, indent=2, ensure_ascii=False)
    if result.get("status")== 'success':
        print('已经授权')
    
    # 也可以检查指定MAC
    # result = client.check_mac("00:11:22:33:44:55")
    
    # 保存数据
    print("\n保存测试数据...")
    test_data = {
        "device_mac": local_mac,
        "sensor": "temperature",
        "value": 25.5,
        "unit": "Celsius",
        "location": "server_room"
    }
    save_result = client.save_result(test_data)
    print("保存结果:", json.dumps(save_result, indent=2, ensure_ascii=False))